package cn.tedu.flowers.controller;


import cn.tedu.flowers.entity.Product;
import cn.tedu.flowers.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;

    @RequestMapping("/product/insert")
    public void insert(Product product, MultipartFile file) throws IOException {
        System.out.println("product = " + product + ", file = " + file);
        String fileName = file.getOriginalFilename();
        //后缀名
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        //唯一文件名
        fileName= UUID.randomUUID()+suffix;
//得到一个日期路径yyyy年MM月dd日 HH小时 mm分 ss秒
        SimpleDateFormat format=
                new SimpleDateFormat("/yyyy/MM/dd/");
        //得到标识当前时间的对象
        Date date =new Date();
        //
        String datePath =format.format(date);
        //
        String dirPath="d:/upload";
        //创建文件对象
        File dirFile =new File(dirPath+datePath);
        //如果不存在创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //
        String filePath =dirPath+datePath+fileName;
        //
        file.transferTo(new File(filePath));

        //把图片路径给到作品对象
        product.setUrl(datePath+fileName);
        //保存到数据库中
        mapper.insert(product);
    }

    @RequestMapping("/product/select")
    public List<Product> select(){
        return mapper.select();
    }

    @RequestMapping("/product/delete")
    public void delete(int id){
        mapper.delete(id);
    }

    @RequestMapping("/product/selectbycid")
    public List<Product> selectByCid(int cid){
        System.out.println("cid = " + cid);
        return mapper.selectByCid(cid);
    }

    @RequestMapping("/product/selectbywd")
    public List<Product> selectByWd(String wd){
        System.out.println("wd = " + wd);
        return mapper.selectByWd(wd);
    }


}
